//
//  CDHomeController.swift
//  CDLiftWithDisplay
//
//  Created by SteveLi on 2017/9/17.
//  Copyright © 2017年 李军桦. All rights reserved.
//

import UIKit

class CDHomeController: UITableViewController {
    //直接懒加载获取模型数据
    lazy var dataArray = CDHomeModel.homeInfos()
    //创建动画用定时属性
    var timer:Timer!
    var num: Int = 1
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //让表格视图自适应cell高度
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
    }
    //开始定时器
    func startTimer() {
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(cellImageAnimation), userInfo: nil, repeats: true)
        }
    }
    //停止定时器
    func stopTimer() {
        if timer != nil {
            //先将定时器从运行循环中退出
            timer.invalidate()
            //在设置为空
            timer = nil
        }
    }
    //视图显示完成
    override func viewDidAppear(_ animated: Bool) {
        startTimer()
    }
    //视图即将消失时停止动画
    override func viewWillDisappear(_ animated: Bool) {
        stopTimer()
    }
    
    
    func cellImageAnimation() {
        //切换图片下标
        num += 1
        if num > 3 {
            num = 1
        }
        //获取第一个cell视图,并且获得cell的图片视图
        let indexP = IndexPath(row: 0, section: 0)
        guard let firstCell = tableView.cellForRow(at: indexP) as? CDHomeCell else {
            return
        }
        
        let cellImgV = firstCell.homeImageView
        //使用核心动画的转场动画来实现
        let imgAniam = CATransition()
        //动画类型
        imgAniam.type = kCATransitionPush
        //动画方向
        imgAniam.subtype = kCATransitionFromRight
        //动画时需要切换的图片
        cellImgV?.image = UIImage(named: "首页\(num)")
        //动画时长
        imgAniam.duration = 2
        //添加动画到需要动画的图片视图图层上
        cellImgV?.layer.add(imgAniam, forKey: nil)
    }
}


extension CDHomeController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "homeCell", for: indexPath) as! CDHomeCell
        //设置cell中的选中状态
        cell.selectionStyle = .none
        //获取对应的模型对象来赋值
        let model = dataArray[indexPath.row]
        //赋值
        cell.model = model
        return cell
    }
    
    
    
    
}


